﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Web.UI.WebControls;
using System.Xml.Linq;

public partial class Catalog_Okna : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
      XDocument xDoc = XDocument.Load("http://www.nbp.pl/kursy/xml/LastA.xml");
      downloadIfModified(@"http://www.nbp.pl/kursy/xml/LastA.xml");
      var records = from elem in xDoc.Descendants("pozycja")
        select elem;
      GenerateTable(records);
    }
    private DataTable CreateDataTable(IEnumerable<XElement> records)
    {
      DataTable dt = new DataTable();

      DataRow dr = null;
      //Create the Columns Definition
      dt.Columns.Add(new DataColumn("nazwa_waluty", typeof(string)));
      dt.Columns.Add(new DataColumn("przelicznik", typeof(string)));
      dt.Columns.Add(new DataColumn("kod_waluty", typeof(string)));
      dt.Columns.Add(new DataColumn("kurs_sredni", typeof(string)));
     
      DataClassesDataContext context = new DataClassesDataContext();
      foreach (var result in records)
      {
        DataRow r = dt.NewRow();
        r["nazwa_waluty"] = result.Element("nazwa_waluty").Value;
        r["przelicznik"]  = result.Element("przelicznik").Value;
        r["kod_waluty"]   = result.Element("kod_waluty").Value;
        r["kurs_sredni"]  = result.Element("kurs_sredni").Value;
        dt.Rows.Add(r);
        KursyA record = new KursyA();
        record.nazwa_waluty = result.Element("nazwa_waluty").Value;
        record.przelicznik = int.Parse(result.Element("przelicznik").Value);
        record.kod_waluty = result.Element("kod_waluty").Value;
        record.kurs_sredni = result.Element("kurs_sredni").Value;
        KursyA oldRecord = context.KursyAs.FirstOrDefault(x => x.kod_waluty == record.kod_waluty);
        if (oldRecord != null)
        {
          if (oldRecord.kurs_sredni != record.kurs_sredni) oldRecord.kurs_sredni = record.kurs_sredni;
          else if (oldRecord.nazwa_waluty != record.nazwa_waluty) oldRecord.nazwa_waluty = record.nazwa_waluty;
          else if (oldRecord.przelicznik != record.przelicznik) oldRecord.przelicznik = record.przelicznik;
          else continue;
        } else context.KursyAs.InsertOnSubmit(record);
      }
      context.SubmitChanges();

      return dt;
    }
    private void GenerateTable(IEnumerable<XElement> records)
    {
      DataTable dt = CreateDataTable(records);
      Table table = new Table();
      TableRow row = null;

      //Add the Headers
      row = new TableRow();
      string[] ColumnNames = new string[]{ "Nazwa waluty",	"Przelicznik",	"Kod waluty",	"Kurs średni" };
      for (int j = 0; j < dt.Columns.Count; j++)
      {
        TableHeaderCell headerCell = new TableHeaderCell();
        headerCell.Text = ColumnNames[j];
        row.Cells.Add(headerCell);
      }
      table.Rows.Add(row);

      //Add the Column values
      for (int i = 0; i < dt.Rows.Count; i++)
      {
        row = new TableRow();
        for (int j = 0; j < dt.Columns.Count; j++)
        {
          TableCell cell = new TableCell();
          cell.Text = dt.Rows[i][j].ToString();
          row.Cells.Add(cell);
        }
        // Add the TableRow to the Table
        table.Rows.Add(row);
      }
      table.CssClass = "table table-bordered table-hover table-condensed";
      table.ID = "ExchangeRates";
      // Add the the Table in the Form
      Panel1.Controls.Add(table);
    }
    
    private void download(string fileUrl)
    {
      HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(fileUrl);
      request.Method = "GET";
      HttpWebResponse response = (HttpWebResponse)request.GetResponse();
      
      string output = Server.MapPath("/Site/App_Code/Sources/" + fileUrl.Split('/').Last());
      saveSourceFile(output, response);
    }

    private void saveSourceFile(string output, HttpWebResponse response)
    {
      Stream strm = response.GetResponseStream(); // Input stream
      FileStream fs = new FileStream(output, FileMode.Create, FileAccess.Write, FileShare.None);

      string eTag = response.Headers[HttpResponseHeader.ETag];
      string ifModifiedSince = response.Headers[HttpResponseHeader.LastModified];

      File.WriteAllText(output + ".stats", eTag + "\n" + ifModifiedSince);
      const int ArrSize = 10000;
      Byte[] barr = new Byte[ArrSize];
      while (true)
      {
        int Result = strm.Read(barr, 0, ArrSize);
        if (Result == -1 || Result == 0)
          break;
        fs.Write(barr, 0, Result);
      }
      fs.Flush();
      fs.Close();
      strm.Close();
      response.Close();
    }

    private void downloadIfModified(string fileUrl)
    {
      HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(fileUrl);
      request.Method = "GET";
      string output = Server.MapPath("/Site/App_Code/Sources/" + fileUrl.Split('/').Last());
      string[] stats = File.ReadAllLines(output+".stats");
      string eTag = stats[0];
      string ifModifiedSince = stats[1];
      try {
         request.Headers[HttpRequestHeader.IfNoneMatch] = eTag;
         request.IfModifiedSince = DateTime.Parse(ifModifiedSince);;
         HttpWebResponse response = (HttpWebResponse)request.GetResponse();
         saveSourceFile(output,response);
      } 
      catch(System.Net.WebException ex)
      {
         if (ex.Response != null)
         {
            using (HttpWebResponse response = ex.Response as HttpWebResponse)
            {
               if (response.StatusCode == HttpStatusCode.NotModified)
               {
                 //MessageBox.Show("File has not been updated since your last request");
                 // Get Data from db
                 File.WriteAllText(output + ".log", "File has not been updated since your last request");
                 return;
               }
               else {
                 //MessageBox.Show(string.Format("Unexpected status code returned: {0}", response.StatusCode));
                 File.WriteAllText(output + ".log", "Unexpected status code returned: "+response.StatusCode);
                 return;
               }
            }
         }
      }
    }
}
